package com.pzh.logistics.service.impl;

import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.mbg.mapper.AddressMapper;
import com.pzh.logistics.mbg.model.Address;
import com.pzh.logistics.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    @Transactional
    public Address add(Address address) {
        addressMapper.insert(address);
        Integer id = address.getAddressId();
        return addressMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public boolean delAddress(Integer addressId, Integer userId) {
        if (addressMapper.deleteByAddressIdAndUserId(addressId, userId) == 1) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Address updateByAddressIdAndUserId(Address address, Integer userId) {
        Address result = addressMapper.selectByPrimaryKey(address.getAddressId());
        if (result == null){
            throw new GlobalException(ResultEnum.ADDRESS_NOT_EXIST);
        }

        if (!result.getUserId().equals(userId)){
            throw new GlobalException(ResultEnum.CHECK_ULTRA_VIRES);
        }
        result = addressMapper.selectByPrimaryKey(address.getAddressId());
        return result;
    }

    @Override
    public List<Address> findByUserId(Integer userId) {
        return addressMapper.findByUserId(userId);
    }

    @Override
    public Address findByAddressId(Integer addressId) {
        return addressMapper.selectByPrimaryKey(addressId);
    }

    @Override
    public Address findByAddressAndUserId(Integer addressId, Integer userId) {
        return addressMapper.findByAddressIdAndUserId(addressId, userId);
    }
}
